package cn.jekun.shop.app.action;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONObject;
import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.shop.common.service.DomainService;

/**
 * 域名
 * @author twj
 *
 */
@SuppressWarnings("serial")
public class DomainAction extends AppBaseAction{
	@Resource(name = DomainService.BEAN_NAME)
	protected DomainService domainService;
	/**
	 * 查询商家域名
	 * @return
	 */
	public String queryDomainByShopId(){
		JSONObject jsonObject = null;
		try{
			String shopId = this.request.getParameter("shopId");
			this.validateLoginApp(); 
			this.validateSign(this.getUserId(),shopId);
			jsonObject = this.domainService.queryDomainByShopId(shopId);
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
		}
	/**
	 * 修改商家域名
	 * @return
	 */
	public String updateDomainByShopId(){
		JSONObject jsonObject = null;
		try{
			String shopId = this.request.getParameter("shopId"); 
			String secondDomain = this.request.getParameter("secondDomain");
			String _secondDomain = null;
			if(!StringUtils.isBlank(secondDomain)){
				
				_secondDomain=secondDomain.replace("http://", "").replace(".storeme.cn", "");
				
				
			}
			
			this.validateLoginApp(); 
			this.validateSign(this.getUserId(),shopId,secondDomain);
			jsonObject = this.domainService.updateDomainByShopId(shopId,_secondDomain);
			if("1".equals(jsonObject.getString("code").trim())){
				this.logService.addMallLog(this.getUserId(), 
						this.getBrowser(), this.getIp(), "商家编码:"+shopId+"二级域名设置成功");//记录操作日志
			}
		} catch (BusinessException e) {
			this.logService.addMallLog(this.getUserId(), 
					this.getBrowser(), this.getIp(), "修改商家域名失败");//记录操作日志
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}
	
	/**
	 * 检查二级域名是否被注册过
	 * @param secondDomain
	 * @return
	 */
	public String checkIsReg(){
		JSONObject jsonObject = null;
		try{
			String shopId = this.request.getParameter("shopId"); 
			String secondDomain = this.request.getParameter("secondDomain");
			this.validateLoginApp(); 
			this.validateSign(this.getUserId(),shopId,secondDomain);
			jsonObject = this.domainService.checkIsReg(shopId,secondDomain);
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}

}
